package vnt.farming;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.R.bool;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebView.FindListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.os.Build;

public class MainActivity extends ActionBarActivity {

	static String DB_NAME = "farming.db";
	AutoCompleteTextView myAutoComplete;
    public ListThuocAdapter myAdapter;
	public SQLiteDatabase myDatabase = null;
	public TblThuoc tblThuoc = null;
	Context context;
	
	TextView hoatChat;
	TextView doiTuong;
	TextView ghiChu;
	TextView cachLy;
	TextView gocThuoc;
	TextView congTy;

	String sActive = "";
	
	Button bntClear;
	Button btnContactDetail;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_main);
		context = this.context;
		
/*
		if (savedInstanceState == null) {
			getSupportFragmentManager().beginTransaction()
					.add(R.id.container, new PlaceholderFragment()).commit();
		}
	*/	
		/*
		String dbPath = Environment.getDataDirectory() + "/data/" + getPackageName() + "/databases/";
		File dbFile = new File(dbPath + DB_NAME);
		if(!dbFile.exists())
		{
			try
			{
				dbFile.mkdir();
				copyDatabase();
			}
			catch(Exception ex1)
			{
				dbPath = ex1.getMessage();
			}
		}
		*/
		/*
		String s = "";
		try
		{
			
			myDatabase = SQLiteDatabase.openDatabase(dbPath + DB_NAME, null, SQLiteDatabase.OPEN_READONLY);
		}
		catch(Exception ex)
		{
			try
			{
				myDatabase = openOrCreateDatabase(DB_NAME, MODE_PRIVATE, null);
				copyDatabase();
				//myDatabase = SQLiteDatabase.openDatabase(DB_NAME, null, SQLiteDatabase.OPEN_READONLY);
			}
			catch(Exception ex1)
			{
				s = ex1.getMessage();
			}
		}
*/
		////\\ Kiem code bang url services.
		//checkActive("active.txt");
		
		//\\ Khong can kiem tra code.
		copyDatabase();
		myDatabase = openOrCreateDatabase("farming.db", MODE_PRIVATE, null);

		hoatChat = (TextView) findViewById(R.id.hoatChat);
		doiTuong = (TextView) findViewById(R.id.doiTuong);
		ghiChu = (TextView) findViewById(R.id.ghiChu);
		cachLy = (TextView) findViewById(R.id.cachLy);
		gocThuoc = (TextView) findViewById(R.id.gocThuoc);
		congTy = (TextView) findViewById(R.id.congTy);

		myAutoComplete = (AutoCompleteTextView) findViewById(R.id.myautocomplete);
		
		
        myAdapter = new ListThuocAdapter(this, R.layout.list_thuoc, new ArrayList<TblThuoc>());
        myAutoComplete.setAdapter(myAdapter);
        //myAdapter.notifyDataSetChanged();
		
		OnItemClickListener itemClickListener = new OnItemClickListener()
		  {
			@Override
            public void onItemClick(AdapterView<?> parent, View arg1, int pos, long id) {
				tblThuoc = myAdapter.getThuocs().get(0);
                RelativeLayout rl = (RelativeLayout) arg1;
                TextView tv = (TextView) rl.getChildAt(0);
                myAutoComplete.setText(tv.getText().toString());
                //myAutoComplete.clearFocus();
                myAutoComplete.selectAll();
                
                if(tblThuoc != null)
                {
                	String prefix = "- ";
            		hoatChat.setText(prefix + tblThuoc.getHoatChat());
            		doiTuong.setText(prefix + tblThuoc.getDoiTuong());
            		ghiChu.setText(prefix + tblThuoc.getGhiChu());
            		cachLy.setText(prefix + tblThuoc.getCachLy());
            		//cachLy.setText("");
            		//String iCachLy = tblThuoc.getCachLy();
            		//if(iCachLy != null)
            			//cachLy.setText("" + iCachLy);
            		gocThuoc.setText(prefix + tblThuoc.getGocThuoc());
            		congTy.setText(prefix + tblThuoc.getCongTy());
            		
            		tblThuoc = null;
            		
            		myAutoComplete.requestFocus();
            		myAutoComplete.setFocusableInTouchMode(true);
                    
            		InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
            		inputManager.hideSoftInputFromWindow(myAutoComplete.getWindowToken(), 0);
                }
			}

        };
        myAutoComplete.setOnItemClickListener(itemClickListener);
		
		bntClear = (Button)findViewById(R.id.btnClear);
		bntClear.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String sEmpty = "";
				myAutoComplete.setText(sEmpty);
        		hoatChat.setText(sEmpty);
        		doiTuong.setText(sEmpty);
        		ghiChu.setText(sEmpty);
        		cachLy.setText(sEmpty);
        		gocThuoc.setText(sEmpty);
        		congTy.setText(sEmpty);
        		
        		tblThuoc = null;
				
				myAutoComplete.requestFocus();
        		myAutoComplete.setFocusableInTouchMode(true);
                
        		InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
        		inputManager.showSoftInput(myAutoComplete, InputMethodManager.SHOW_FORCED);
			}
		});

		btnContactDetail = (Button)findViewById(R.id.btnContactDetail);
		btnContactDetail.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
/*				
				AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(v.getContext(), R.style.AlertDialogCustom));
				//\\ Set title view.
				TextView title = new TextView(v.getContext());
				title.setText("ThÃ´ng tin liÃªn há»‡");
				title.setGravity(Gravity.CENTER_HORIZONTAL);
				title.setTextSize(20); 
				title.setTextColor(getResources().getColor(R.color.dialog_title));
				title.setBackgroundColor(getResources().getColor(R.color.dialog_background));
				alert.setCustomTitle(title);
				//alert.setTitle("ThÃ´ng tin liÃªn há»‡");
				StringBuilder sb = new StringBuilder();
				sb.append("Giao diá»‡n pháº§n má»�m vÃ  ná»™i dung Ä‘Æ°á»£c phÃ¡t "); 
				sb.append("triá»ƒn bá»Ÿi: Tháº¡c sÄ© khoa há»�c cÃ¢y trá»“ng \"LÆ°u Minh Tuáº¥n\". ");
				sb.append("Náº¿u ngÆ°á»�i dÃ¹ng phÃ¡t hiá»‡n cÃ³ báº¥t cá»© sai sÃ³t nÃ o hay gÃ³p ");
				sb.append("Ã½ phÃ¡t triá»ƒn xin vui lÃ²ng Ä‘Ã³ng gÃ³p vá»›i tÃ¡c giáº£ Ä‘á»ƒ sáº£n "); 
				sb.append("pháº©m Ä‘Æ°á»£c hoÃ n thiá»‡n hÆ¡n, ngÆ°á»�i dÃ¹ng cÃ³ Ä‘Ã³ng gÃ³p sáº½ "); 
				sb.append("nháº­n Ä‘Æ°á»£c KEY báº£n quyá»�n miá»…n phÃ­. LiÃªn há»‡: 0919 056 "); 
				sb.append("783 hoáº·c Chi cá»¥c BVTV An Giang: 0763 953 622.");
				//\\ Set content view.
				final TextView info = new TextView(v.getContext());
				info.setText(sb.toString());
				info.setTextColor(getResources().getColor(R.color.dialog_content));
				info.setBackgroundColor(getResources().getColor(R.color.dialog_background));
				alert.setView(info);
				//alert.setMessage(sb.toString());
				alert.setPositiveButton("Ä�Ã³ng", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					}
				});
				
				//alert.setd
				//\\ Show dialog.
				alert.show();
*/				
			    final Dialog dialog = new Dialog(v.getContext());
			    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			    dialog.setContentView(R.layout.dialog_custom);
			    // BIND
			    //TextView title = (TextView) dialog.findViewById(R.id.dialogTitle);
			    //WebView text = (WebView) dialog.findViewById(R.id.dialogText);
			    //WebSettings settings = text.getSettings();
			    //settings.setDefaultTextEncodingName("utf-8");
			    //text.loadData(getString(R.string.dialog_content), "text/html", "utf-8");
			    Button button = (Button) dialog.findViewById(R.id.dialogOK);
			    //LinearLayout line = (LinearLayout) dialog.findViewById(R.id.dialogLine);

			    // SET WIDTH AND HEIGHT
			    //DisplayMetrics displaymetrics = new DisplayMetrics();
			    //getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
			    //int width = (int) (displaymetrics.widthPixels * 0.85);
			    //int height = (int) (displaymetrics.heightPixels * 0.60);
			    //WindowManager.LayoutParams params = getWindow().getAttributes();
			    //params.width = width;
			    //dialog.getWindow().setLayout(width, height);


			    // SET TEXTS
			    //text.setText("message");
			    //button.setText("text1");


		        button.setOnClickListener(new View.OnClickListener() {
		            @Override
		            public void onClick(View v) {
		                dialog.dismiss();
		            }
		        });


			    // SHOW
			    dialog.show();

			}
		});
       
        TextWatcher textWatcher = new TextWatcher()
        {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
		        try{
		            // get suggestions from the database
		            ArrayList<TblThuoc> myObjs = read(s.toString());
		            myAdapter.setThuocs(myObjs);
		            
		            // update the adapter
		            myAdapter = new ListThuocAdapter(myAdapter.getContext(), R.layout.list_thuoc, myObjs);
		             
		            myAutoComplete.setAdapter(myAdapter);
		            // update the adapater
		            myAdapter.notifyDataSetChanged();
		        } catch (NullPointerException e) {
		            e.printStackTrace();
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}
		};
        
        // add the listener so it will tries to suggest while the user types
        myAutoComplete.addTextChangedListener(textWatcher);

		myAutoComplete.requestFocus();
		myAutoComplete.setFocusableInTouchMode(true);
        
		InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
		inputManager.showSoftInput(myAutoComplete, InputMethodManager.SHOW_FORCED);
	}

	private String getSysInfo()
	{
		StringBuilder sysinfo = new StringBuilder();
		sysinfo.append(Build.MANUFACTURER);
		sysinfo.append(Build.MODEL);
		sysinfo.append(Build.PRODUCT);
		sysinfo.append(Build.BOARD);
		sysinfo.append(Build.DEVICE);
		return sysinfo.toString();
	}
	
	private boolean checkActive(final String filename)
	{
		boolean result = false;
		// Check active file.
		sActive = readFromFile(filename);
		// Get system info.
		final String sysinfo = getSysInfo();
		if(sActive == null || sActive == "")
		{
			// Show confirm code.
			AlertDialog.Builder alert = new AlertDialog.Builder(this);
			alert.setTitle("Vui lòng nhập mã kích hoạt");
			alert.setMessage("Nhập mã");
			// Set an EditText view to get user input 
			final EditText input = new EditText(this);
			alert.setView(input);
			// Ok click.
			alert.setPositiveButton("Gởi", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
					String sActive = input.getText().toString();
					sActive = "http://bvtv-angiang.rhcloud.com/active/active/"+ sActive +"/" + sysinfo;
					sActive = getContentURL(sActive);
					if(sActive.equals("1"))
					{
						copyDatabase();
						myDatabase = openOrCreateDatabase("farming.db", MODE_PRIVATE, null);
						writeToFile(sysinfo, filename);
					}
				}
			});
			// Cancel click.
			alert.setNegativeButton("Hủy", new DialogInterface.OnClickListener() {
			  public void onClick(DialogInterface dialog, int whichButton) {
			  }
			});

			alert.show();
		}
		// Actived.
		else if(sActive.equals(sysinfo))
		{
			// Copy db and open db.
			copyDatabase();
			myDatabase = openOrCreateDatabase("farming.db", MODE_PRIVATE, null);

			result = true;
		}
		return result;
	}
	
	private String getContentURL(String url)
	{
		String result = "";
		try
		{
		    HttpClient httpclient = new DefaultHttpClient();
		    HttpResponse response = httpclient.execute(new HttpGet(url));
		    StatusLine statusLine = response.getStatusLine();
		    if(statusLine.getStatusCode() == HttpStatus.SC_OK){
		        ByteArrayOutputStream out = new ByteArrayOutputStream();
		        response.getEntity().writeTo(out);
		        out.close();
		        result = out.toString();
		    } else{
		        //Closes the connection.
		        response.getEntity().getContent().close();
		        throw new IOException(statusLine.getReasonPhrase());
		    }
		}
		catch(IOException ex)
		{
			
		}
		return result;
	}
	
	private void copyDatabase(){
		String dbPath = Environment.getDataDirectory() + "/data/" + getPackageName() + "/databases/";
		File dbFile = new File(dbPath + DB_NAME);
		if(!dbFile.exists())
		{
			try
			{
				dbFile = new File(dbPath);
				if(!dbFile.exists())
					dbFile.mkdirs();
				InputStream myInput = getAssets().open(DB_NAME);
				//String dbPath = Environment.getDataDirectory() + "/data/" + getPackageName() + "/databases/";
				OutputStream myOutput = new FileOutputStream(dbPath + DB_NAME);
				
				byte[] buffer = new byte[1024];
				int length;
				while ((length = myInput.read(buffer)) > 0)
				{
					myOutput.write(buffer, 0, length);
				}
				myOutput.flush();
				myOutput.close();
				myInput.close();
			}
			catch(Exception ex1)
			{
				dbPath = ex1.getMessage();
			}
		}
	}

	// Read records related to the search term
    public ArrayList<TblThuoc> read(String searchTerm) {
 
    	if(searchTerm.equals(""))
    	{
    		return new ArrayList<TblThuoc>();
    	}
        // select query
        String sql = "";
        sql += "SELECT * FROM TblThuoc";
        sql += " WHERE TenThuoc LIKE '" + searchTerm + "%'";
        sql += " ORDER BY TenThuoc";
        //sql += " LIMIT 0,5";
 
        //myDatabase = openOrCreateDatabase("farming.db", MODE_PRIVATE, null);
        // execute the query
        Cursor cursor = myDatabase.rawQuery(sql, null);
 
        int recCount = cursor.getCount();
         
        ArrayList<TblThuoc> ObjectItemData = new ArrayList<TblThuoc>();
        int x = 0;
         
        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                TblThuoc myObject = new TblThuoc();
                myObject.setMaSo(cursor.getInt(cursor.getColumnIndex("MaSo")));
                myObject.setTenThuoc(cursor.getString(cursor.getColumnIndex("TenThuoc")));
                myObject.setHoatChat(cursor.getString(cursor.getColumnIndex("HoatChat")));
                myObject.setDoiTuong(cursor.getString(cursor.getColumnIndex("DoiTuong")));
                myObject.setGhiChu(cursor.getString(cursor.getColumnIndex("GhiChu")));
                /*
                int idxCachLy = cursor.getColumnIndex("CachLy");
                if(!cursor.isNull(idxCachLy))
                {
                	myObject.setCachLy(cursor.getInt(idxCachLy));
                }
                */
                myObject.setCachLy(cursor.getString(cursor.getColumnIndex("CachLy")));
                myObject.setGocThuoc(cursor.getString(cursor.getColumnIndex("GocThuoc")));
                myObject.setCongTy(cursor.getString(cursor.getColumnIndex("CongTy")));

                ObjectItemData.add(myObject);
                 
                x++;
                 
            } while (cursor.moveToNext());
        }
 
        cursor.close();
        //myDatabase.close();
 
        return ObjectItemData;
         
    }
	
	public ArrayList<TblThuoc> getAll()
	{
		ArrayList<TblThuoc> tblThuocs = new ArrayList<TblThuoc>();
		myDatabase = openOrCreateDatabase("farming.db", MODE_PRIVATE, null);
		Cursor c = myDatabase.query("TblThuoc", null, null, null, null, null, null);
		c.moveToFirst();
		TblThuoc tblThuoc;
		String data="";
		while(c.isAfterLast()==false)
		{
			tblThuoc = new TblThuoc();
			tblThuoc.setMaSo(c.getInt(0));
			tblThuoc.setTenThuoc(c.getString(1));
			tblThuoc.setHoatChat(c.getString(2));
			tblThuoc.setDoiTuong(c.getString(3));
			tblThuoc.setGhiChu(c.getString(4));
			tblThuoc.setCachLy(c.getString(5));
			tblThuoc.setGocThuoc(c.getString(6));
			tblThuoc.setCongTy(c.getString(7));
			
			tblThuocs.add(tblThuoc);
			c.moveToNext();
		}
		c.close();
		myDatabase.close();
		return tblThuocs;
	}

	public TblThuoc getById(int pId)
	{
		TblThuoc tblThuoc = null;
		myDatabase = openOrCreateDatabase("farming.db", MODE_PRIVATE, null);
		Cursor c = myDatabase.query("TblThuoc", null, "MaSo=" + pId, null, null, null, null);
		if(c != null)
		{
			if(c.moveToFirst())
			{
				tblThuoc = new TblThuoc();
				tblThuoc.setMaSo(c.getInt(0));
				tblThuoc.setTenThuoc(c.getString(1));
				tblThuoc.setHoatChat(c.getString(2));
				tblThuoc.setDoiTuong(c.getString(3));
				tblThuoc.setGhiChu(c.getString(4));
				tblThuoc.setCachLy(c.getString(5));
				tblThuoc.setGocThuoc(c.getString(6));
				tblThuoc.setCongTy(c.getString(7));
			}
			c.close();
		}
		myDatabase.close();
		return tblThuoc;
	}

	
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_main, container,
					false);
			
			return rootView;
		}
	}

	
	private void writeToFile(String data, String filename) {
	    try {
	        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(filename, Context.MODE_PRIVATE));
	        outputStreamWriter.write(data);
	        outputStreamWriter.close();
	    }
	    catch (IOException e) {
	        Log.e("Exception", "File write failed: " + e.toString());
	    } 
	}


	private String readFromFile(String filename) {

	    String ret = "";

	    try {
	        InputStream inputStream = openFileInput(filename);

	        if ( inputStream != null ) {
	            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
	            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
	            String receiveString = "";
	            StringBuilder stringBuilder = new StringBuilder();

	            while ( (receiveString = bufferedReader.readLine()) != null ) {
	                stringBuilder.append(receiveString);
	            }

	            inputStream.close();
	            ret = stringBuilder.toString();
	        }
	    }
	    catch (FileNotFoundException e) {
	        Log.e("login activity", "File not found: " + e.toString());
	    } catch (IOException e) {
	        Log.e("login activity", "Can not read file: " + e.toString());
	    }

	    return ret;
	}
}
